//
//  ChatViewController.m
//  ChatForHot
//
//  Created by FLY on 2018/10/16.
//  Copyright © 2018年 FLY. All rights reserved.
//

#import "ChatViewController.h"
#import "UserPhotoUploadViewController.h"
#import "HCPhotoManager.h"
#import "AppDelegate.h"
#import "UserInfoController.h"
#import "ChatDemoHelper.h"
#import "NoVipView.h"
@interface ChatViewController ()<UploadPhotoSelectedDelegate,NoVipViewDelegate>

@property (nonatomic, strong) NoVipView *HOTCHATnoVipView;

@end

@implementation ChatViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.backgroundColor = HOTCHATrgb(237, 237, 237);
    self.showRefreshHeader = YES;
    [self HOTCHATrequestuserInfo];
    [self HOTCHATgetIfNoVipAndInfo];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"chatuser"] style:(UIBarButtonItemStylePlain) target:self action:@selector(HOTCHATLookuserInfo)];
}
- (void)HOTCHATgetIfNoVipAndInfo{
    
    if (HOTCHATAPPINFO.isVIP.integerValue != 1) {
        // no vip
        if ([self.conversation.conversationId isEqualToString:@"88460527"]) {
            //ADMINIID 客服
            return;
        }
        [self HOTCHATgetNoVipInfo];
    }
}
- (NoVipView *)HOTCHATnoVipView{
    if (_HOTCHATnoVipView == nil) {
        _HOTCHATnoVipView = [[NoVipView alloc] init];
        _HOTCHATnoVipView.delegate = self;
        @weakify(self);
        [[_HOTCHATnoVipView rac_signalForSelector:@selector(HOTCHATbtnAction)] subscribeNext:^(RACTuple * _Nullable x) {
            @strongify(self);
            UIView *window = [[UIApplication sharedApplication].delegate window];
            [self HOTCHATstartLoadingInView:window];
            
        }];
        [[_HOTCHATnoVipView rac_signalForSelector:@selector(HOTCHATcloseview)] subscribeNext:^(RACTuple * _Nullable x) {
            @strongify(self);
            [self.HOTCHATnoVipView removeFromSuperview];
            [self.navigationController popViewControllerAnimated:YES];
        }];
    }
    return _HOTCHATnoVipView;
}
- (void)HOTCHATbuyVipFinishFed{
    
    [self.HOTCHATnoVipView removeFromSuperview];
    [self HOTCHATstopLoading];
}
- (void)HOTCHATServiceAction{
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://sites.google.com/view/chatforhotterms"]];
}

- (void)HOTCHATpolicyAction{
   
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://sites.google.com/view/chatforhotpolicy"]];
}
- (void)HOTCHATgetNoVipInfo{
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc]init];
    [dic setValue:HOTCHATAPPINFO.appid forKey:@"appid"];
    
    [self HOTCHATstartLoading];
    
    [NetWorkTool HOTCHATRequestWithStringURL:NOVIPINFO_URL progress:^(NSProgress *uploadProgress) {
        
    } RequestWay:@"GET" Parma:dic SuccessBlock:^(BOOL isSucess, NSDictionary * _Nonnull resultDictionary) {
        if ([resultDictionary[@"code"] isEqualToString:@"0"]) {
            [self HOTCHATstopLoading];
            
            if (resultDictionary != nil && resultDictionary[@"data"] != nil) {
                
                [[NSUserDefaults standardUserDefaults] setValue:resultDictionary[@"data"] forKey:@"freeThreeDays"];
                [HOTCHATAPPINFO HOTCHATreset];
                self.HOTCHATnoVipView.dataDic = resultDictionary[@"data"];
                [self.HOTCHATnoVipView show];
            }else{
                
                [self HOTCHATstopLoading];
                [self dismissViewControllerAnimated:YES completion:^{
                    
                }];
                [self HOTCHATshowMessage:NSLocalizedString(@"msgShow22", nil)];
            }
            
        }else{
            [self HOTCHATstopLoading];
            [self dismissViewControllerAnimated:YES completion:^{
                
            }];
            [self HOTCHATshowMessage:NSLocalizedString(@"msgShow22", nil)];
        }
    } FailureBlock:^(NSError * _Nonnull error) {
        [self HOTCHATstopLoading];
        [self dismissViewControllerAnimated:YES completion:^{
            
        }];
        [self HOTCHATshowMessage:NSLocalizedString(@"msgShow22", nil)];
    }];
}

- (void)HOTCHATrequestuserInfo{
    if (self.HOTCHATuserHeadPic.length == 0) {
        if (![self.userModel HOTCHATgetIMImfoFromDBByImUser:self.conversation.conversationId]) {
            
//            __weak typeof (self) weakself = self;
            NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
            [dic setValue:self.conversation.conversationId forKey:@"accountNumber"];
            
            [NetWorkTool HOTCHATRequestWithStringURL:ACCOUNTNUMBERGETACCOUNTINFO_URL progress:^(NSProgress * _Nonnull progress) {
                
            } RequestWay:@"GET" Parma:dic SuccessBlock:^(BOOL isSucess, NSDictionary * _Nonnull resultDictionary) {
                if ([resultDictionary[@"code"] integerValue] == 0) {
                    
                    [self.userModel setValuesForKeysWithDictionary:resultDictionary[@"data"]];
                    [self.userModel HOTCHATsaveIMUserInfo];
                    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
                    self.HOTCHATuserHeadPic = self.userModel.headPic;
                    
                }
            } FailureBlock:^(NSError * _Nonnull error) {
                
            }];
            
        }else{
            self.HOTCHATuserHeadPic = self.userModel.headPic;
        }
    }
    [self.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //自动回复功能的一些
//    [self HOTCHATgetMsgCurrentID:YES];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [self.view endEditing:YES];
    
    [[ChatDemoHelper shareHelper].HOTCHATtabbarVC HOTCHATsetupUnreadMessageCount];
}
- (void)tableViewDidTriggerHeaderRefresh {
//    if ([[ChatDemoHelper shareHelper] isFetchHistoryChange]) {
        NSString *startMessageId = nil;
        if ([self.messsagesSource count] > 0) {
            startMessageId = [(EMMessage *)self.messsagesSource.firstObject messageId];
        }
        
        NSLog(@"startMessageID ------- %@",startMessageId);
        [EMClient.sharedClient.chatManager asyncFetchHistoryMessagesFromServer:self.conversation.conversationId
                                                              conversationType:self.conversation.type
                                                                startMessageId:startMessageId
                                                                      pageSize:10
                                                                    completion:^(EMCursorResult *aResult, EMError *aError)
         {
             [super tableViewDidTriggerHeaderRefresh];
         }];
        
//    }
//else {
//        [super tableViewDidTriggerHeaderRefresh];
//    }
}
//相册
- (void)moreViewPhotoAction:(EaseChatBarMoreView *)moreView
{

    self.isPrivatePhoto = NO;
    // Hide the keyboard
    [self.chatToolbar endEditing:YES];
    
    // Pop image picker
    [self HOTCHATopenPhotoView];
    
    self.isViewDidAppear = NO;
    [[EaseSDKHelper shareHelper] setIsShowingimagePicker:YES];
    //FROM_SEND_NORMAL_IMAGE,发送普通图片,0
}
//私密照片
- (void)moreViewTakePicAction:(EaseChatBarMoreView *)moreView
{

    self.isPrivatePhoto = YES;
    // Hide the keyboard
    [self.chatToolbar endEditing:YES];
    
    [self HOTCHATopenPhotoView];
    
    self.isViewDidAppear = NO;
    [[EaseSDKHelper shareHelper] setIsShowingimagePicker:YES];
    //FROM_SEND_PRIVATE_PHOTO,发送私密图片,0
}
- (void)sendPrivatePhoto:(NSString *)photo{
    self.isViewDidAppear = YES;
    [[EaseSDKHelper shareHelper] setIsShowingimagePicker:NO];
    
    if (photo) {
        NSString *urlStr = [NSString stringWithFormat:@"%@%@",APIHEADER,self];
        NSURL *url = [NSURL URLWithString:urlStr];
        YYImageCache *cache = [YYImageCache sharedCache];
        UIImage *img = [cache getImageForKey:url.absoluteString withType:YYImageCacheTypeMemory];// imageFromMemoryCacheForKey:];
        if (img == nil) {
            img = [cache getImageForKey:url.absoluteString withType:YYImageCacheTypeDisk];
        }
        if (img) {
            [self sendImageMessage:img];
            return;
        }
        NSLog(@"start");
        NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
        NSURLSession *session = [NSURLSession sharedSession];
        NSURLSessionDataTask *ONENIGHTtask = [session dataTaskWithRequest:request
                                                        completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
                                                            //                                                    NSString *dataStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                                            //                                                    NSLog(@"img %@", dataStr);
                                                            NSLog(@"img _%@",data);
                                                            if (data) {
                                                                [self sendImageMessageWithData:data];
                                                            }
                                                        }];
        [ONENIGHTtask resume];
        NSLog(@"end");
    }
}
- (void)HOTCHATopenPhotoView{
    UserPhotoUploadViewController *pv = [[UserPhotoUploadViewController alloc] init];
    pv.maxCount = 1;
    pv.delegate = self;
    [self.navigationController pushViewController:pv animated:YES];
}
- (void)HOTCHATselectedPhotoArray:(NSArray *)array{
    if (array.count > 0) {
        id obj = [array firstObject];
        if ([obj isKindOfClass:[UIImage class]]) {
            [self sendImageMessage:obj];
        }else if ([obj isKindOfClass:[HCAssetModel class]]){
            HCAssetModel *model = obj;
            NSData *imgData = [self fetchDataFromAsset:model.asset];
            if (imgData) {
                [self sendImageMessageWithData:imgData];
            }
        }
    }
}
- (NSData *)fetchDataFromAsset:(PHAsset *)asset {
    __block NSData *tmpData = [NSData data];
    
    // Image
    if (asset.mediaType == PHAssetMediaTypeImage) {
        PHImageRequestOptions *request = [PHImageRequestOptions new];
        request.version = PHImageRequestOptionsVersionCurrent;
        request.deliveryMode = PHImageRequestOptionsDeliveryModeHighQualityFormat;
        request.resizeMode = PHImageRequestOptionsResizeModeNone;
        request.synchronous = YES;
        
        [[PHImageManager defaultManager] requestImageDataForAsset:asset
                                                          options:request
                                                    resultHandler:
         ^(NSData *imageData, NSString *dataUTI, UIImageOrientation orientation, NSDictionary *info) {
             tmpData = [NSData dataWithData:imageData];
         }];
    }
    
    return tmpData;
}
- (NSDictionary *)HOTCHATextendPhotoExt{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    [dic setValue:(self.isPrivatePhoto ? @4002 : @4001) forKey:@"imageType"];
    [dic setValue:HOTCHATAPPINFO.nickName forKey:@"nickName"];
    [dic setValue:HOTCHATAPPINFO.headPic forKey:@"headPic"];
    [dic setValue:HOTCHATAPPINFO.code forKey:@"vip"];
    [dic setValue:[NSString stringWithFormat:@"%ld",(long)self.chatType] forKey:CHATTYPE];
    return dic;
}
- (UserInfoModel *)userModel{
    if (_userModel == nil) {
        _userModel = [[UserInfoModel alloc] init];
    }
    return _userModel;
}
- (void)avatarViewSelcted:(id<IMessageModel>)model{
    
    if (!model.isSender) {
        //接收方 看详情
        [self HOTCHATLookuserInfo];
    }
    
    self.scrollToBottomWhenAppear = NO;
}
- (void)HOTCHATLookuserInfo{
    UserInfoController *VC = [[UserInfoController alloc] init];
    VC.isIMid = YES;

    VC.IMID = self.conversation.conversationId;
    [self.navigationController pushViewController:VC animated:YES];
}
//moretoolbar action
- (void)moreView:(EaseChatBarMoreView *)moreView didItemInMoreViewAtIndex:(NSInteger)index{
    
    [self.chatToolbar endEditing:YES];
    
    switch (index) {
        case 0:
        {
            
        }
            break;
            
        default:
            break;
    }
}
@end
